<template>
  <div class="xu-table">
    <div class="xu-table">
      <el-table :data="data" v-loading="loading">
        <template v-for="(option, index) in options">
          <el-table-column v-bind="option.attrs" :key="index" v-if="option.buttons">
            <template slot-scope="scope">
              <slot :name="option.attrs.prop">
                <el-tooltip :content="button.label" v-for="(button, idx) in option.buttons" :key="idx">
                  <el-popconfirm
                    :title="button.title || '确认删除么？'"
                    v-if="button.type === 'popover'"
                    @confirm="typeof button.click === 'function' ? button.click(scope) : ''"
                  >
                    <el-button slot="reference" type="danger" :icon="button.icon" size="small" />
                  </el-popconfirm>
                  <el-button
                    v-else
                    :type="button.type || 'primary'"
                    :icon="button.icon"
                    size="small"
                    @click="typeof button.click === 'function' ? button.click(scope) : ''"
                  />
                </el-tooltip>
              </slot>
            </template>
          </el-table-column>
          <el-table-column v-bind="option.attrs" :key="index" v-else>
            <template slot-scope="scope">
              <slot :name="option.attrs.prop" v-bind="scope">{{ scope.row[option.attrs.prop] }}</slot>
            </template>
          </el-table-column>
        </template>
      </el-table>
    </div>
    <div class="page">
      <el-pagination
        background
        :page-size="pagination.pageSize"
        :page-sizes="pagination.pageSizes"
        :current-page="pagination.currentPage"
        :layout="pagination.layout"
        :total="pagination.total"
        :hide-on-single-page="pagination.hideSinglePage"
        @size-change="pagination.sizeChange"
        @current-change="pagination.currentChange"
      />
    </div>
  </div>
</template>

<script>
/**
 * @param loading 加载状态
 * @param pager 分页配置
 * @param data 数据源配置
 * @param options 表格字段配置
 */
const defaultPager = {
  show: true,
  currentPage: 1,
  pageSize: 10,
  pageSizes: [10, 20, 30, 50, 100],
  total: 0,
  layout: 'total, sizes, prev, pager, next, jumper',
  hideSinglePage: true,
  sizeChange: () => {},
  currentChange: () => {}
}
export default {
  name: 'XuTable',
  props: {
    loading: Boolean,
    pager: {
      type: Object,
      default: () => defaultPager
    },
    data: {
      type: Array,
      default: () => []
    },
    options: {
      type: Array,
      default: () => []
    }
  },
  data () {
    return {
      defaultPager
    }
  },
  computed: {
    pagination () {
      return { ...this.defaultPager, ...this.pager }
    }
  }
}
</script>

<style lang="scss" scoped>
.xu-table {
  .page {
    text-align: center;
    margin-top: 15px;
  }
}
</style>
